<?php

namespace App\Http\Middleware\CallingCards;

use App\Models\FeishuCallingCard\FeishuCallingCardFranchisee;
use App\Service\CallingCards\WechatService;
use App\Service\OpenShop\Merchant\MerchantAuth;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class MerchantAppAuth
{
    public static $userId     = 0;
    public static $userInfo   = [];
    public static $franchisee = null;

    /**
     * 验证商家APP是否登录
     * @param Request $request
     * @param Closure $next
     * @return JsonResponse|mixed
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function handle(Request $request, Closure $next)
    {
        $shopId  = (int)$request->header('shopId');
        $brandId = (int)$request->header('brandId');
        $jwt     = (string)$request->header('authorization');

        $userInfo = MerchantAuth::userinfoWithShopAuth($jwt, $brandId, $shopId);
        if (null === $userInfo) {
            return response()->json([
                'code' => 401,
                'msg'  => '尚未登录或者登录凭证失效1',
            ]);
        }
        self::$userId   = $userInfo['id'] ?? 0;
        self::$userInfo = $userInfo;
        if (self::$userId < 1) {
            return response()->json([
                'code' => 401,
                'msg'  => '尚未登录或者登录凭证失效2',
            ]);
        }
        if ($shopId == -1) {
            return $next($request);
        }
        $this->checkFranchisee($shopId);
        $shopLists = $userInfo['shopLists'] ?? [];
        if (in_array($shopId, array_column($shopLists, 'id'))) {

            return $next($request);
        }
        return response()->json([
            'code' => 403,
            'msg'  => '无权限操作此店铺',
        ]);
    }

    public function checkFranchisee($shopId)
    {
        static::$franchisee = FeishuCallingCardFranchisee::firstOrNew([
            'uid' => static::$userId,
        ]);
        if (!static::$franchisee->id) {
            static::$franchisee->position = '夸父炸串合伙人';
        }
        static::$franchisee->save();
    }
}
